# -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 22:32:48 2020

@author: xiong
"""
import xlrd
import xlwt
import openpyxl
from xlutils.copy import copy    
import random
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import xlrd
import xlwt
from xlutils.copy import copy    


def get_class(s):
    result = "".join(i for i in s if ord(i) < 256)
    result = result.replace("\n","",111)
    result = result.replace(". ",".",111)
    result = result.lstrip()
    result = result.replace(" ","_",111)
    result = result.replace(".",". ",111)
    
    result = result.replace("_a"," a",5)
    result = result.replace("_b"," b",5)
    result = result.replace("_c"," c",5)
    result = result.replace("_d"," d",5)
    result = result.replace("_e"," e",5)
    result = result.replace("_f"," f",5)
    result = result.replace("_g"," g",5)
    
    result = result.replace("_h"," h",5)
    result = result.replace("_i"," i",5)
    result = result.replace("_j"," j",5)
    result = result.replace("_k"," k",5)
    result = result.replace("_l"," l",5)
    result = result.replace("_m"," m",5)
    result = result.replace("_n"," n",5)
    
    result = result.replace("_o"," o",5)
    result = result.replace("_p"," p",5)
    result = result.replace("_q"," q",5)
    
    result = result.replace("_r"," r",5)
    result = result.replace("_s"," s",5)
    result = result.replace("_t"," t",5)
    
    result = result.replace("_u"," u",5)
    result = result.replace("_v"," v",5)
    result = result.replace("_w"," w",5)
    
    result = result.replace("_x"," x",5)
    result = result.replace("_y"," y",5)
    result = result.replace("_z"," z",5)
    result = result.replace("Subordo_Liliineae","Subordo Liliineae",5)
    
    
    result2 = "".join(i for i in s if ord(i) >= 256)
    result2 = result2.replace("门","门_",5)
    result2 = result2.replace("纲","纲_",5)
    result2 = result2.replace("目","目_",5)
    result2 = result2.replace("族","族_",5)
    result2 = result2.replace("科","科_",5)
    result2 = result2.replace("属","属_",5)
    result2 = result2.replace("组","组_",5)
    result2 = result2.replace("群","群_",5)
    result2 = result2.replace("系","系_",5)
    

    if result2[len(result2)-1] == "_" :
        result2 = result2[:-1]

    if result.count("_") == result2.count("_"):
        return[result,result2]
    else:
        return[result,result2,'分离失败 检查空格']
    
    
    
    
    
def searchandcatch(sheet0,key):
    Txt = ''
    driver.get('http://www.iplant.cn/info/'+sheet0.cell(i,j).value+'?t=z') 
    
    if len(sheet0.cell(i,j).value) > 0: 
        classTextList = ['error','because not found']
        try:
            classTextList = get_class(driver.find_element_by_xpath('//*[@id="frpsclassdiv"]').text)
        except :
            pass

        
    
#       soup = BeautifulSoup(driver.current_url,'lxml')
        try:
            Txt = driver.find_element_by_xpath('//*[@id="frpscontext"]').text

        except:
            pass 
        driver.get('http://www.iplant.cn/info/'+sheet0.cell(i,j).value)
        try:
            Txt+=append(driver.find_element_by_xpath('//*[@id="info_mp11"]/div').text)
        except:
            pass    
        
        A = ['','针叶','阔叶','叶阔','簇生叶','叶退化','攀援','直立','根茎']
        B = ['','常绿','棕榈','树蕨','落枝','丝兰','麻黄','垫状','散生','丛生','密丛','疏丛']
        C = ['','乔木','灌木','竹类','禾草','苔草','藤本','寄生','一年生','多年生','挺水','浮叶','漂浮','沉水','苔藓','地衣','藻类']
        D = ['','小半灌木']
        E = ['','半灌木']
        HUH = list(set(A+B+C+D+E))
        HUH.remove('')
        
        

        return [searchKeyword(HUH,Txt),classTextList]
        
        
        
def searchKeyword(keywordList,TXT):
    Name = []
    nameSource = ['']
    for item in keywordList:
        while item in TXT and item!= '':
            Name.append(item)
            nameSource.append(TXT[max(TXT.index(item)-6,0):TXT.index(item)+6+len(item)])
            str_list = list(item)
            str_list.insert(1,'d')
            TXT = TXT.replace(item,''.join(str_list),1)
        if nameSource[-1]!='我是分隔符':
            nameSource.append('我是分隔符')
    return[list(set(Name)),nameSource]



chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
path = r'C:\Users\xiong\Downloads\chromedriver.exe'
driver = webdriver.Chrome(executable_path=path, chrome_options=chrome_options)#by xiong
path = r'C:\Users\xiong\Desktop\汇总4.xlsx' 
path2 = r'C:\Users\xiong\Desktop\123.xls' #空表 要建有两个工作表
path3 = r'C:\Users\xiong\Desktop\1234.xls' #输出路径
driver.get('http://www.iplant.cn') 
workbook0 = xlrd.open_workbook(path) 
sheet1 = workbook0.sheet_by_index(0)
sheet0 = workbook0.sheet_by_index(0)

workbook99 = xlrd.open_workbook(path2)
workbook = copy(workbook99)

sheet = workbook.get_sheet(0)
sheetclass = workbook.get_sheet(1)
list11 = []
iInlist = []
for i in range (0,sheet1.ncols):
    list11.append(sheet1.cell(0,i).value)
for j in list11:
    if '区系' in j:
        iInlist.append(list11.index(j)-6)
        list11[list11.index(j)] = ''
banList = []
QQ = 0
for j in [0]: #lie
    for i in range(1,sheet0.nrows):  #hang
        if len(sheet0.cell(i,j).value.strip()) > 0 and sheet0.cell(i,j).value.strip() not in banList  : 
            banList.append(sheet0.cell(i,j).value.strip())
            resultList = searchandcatch(sheet0,sheet0.cell(i,j).value)
            writeList  = resultList[0]
            if len (writeList[0])+len (writeList[1])  >=0:
                sheet.write(QQ,0,label = sheet0.cell(i,j).value)
                sheet.write(QQ,1,label = ','.join(writeList[0]))
                writ4 = ','.join(writeList[1])
                writelist2 = writ4.split('我是分隔符')
                for gg in range(1,len(writelist2)+1):
                    sheet.write(QQ,1+gg,label = writelist2[gg-1])
                print([sheet0.cell(i,j).value,writeList[0],writelist2])
                
            
            classTextList = resultList[1]
            if len (classTextList) == 2:
                sheetclass.write(QQ,0,label = classTextList[1])
                sheetclass.write(QQ,1,label = classTextList[0])
            else :
                sheetclass.write(QQ,0,label = classTextList[1])
                sheetclass.write(QQ,1,label = classTextList[0])
                sheetclass.write(QQ,2,label = classTextList[2])
            
            QQ+=1   
            workbook.save(path3)  

driver.exit()